package net.bblbs.zhongrx.util;

import android.content.Context;

import net.bblbs.zhongrx.db.FieldMapping;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * Created by qxb on 2017/4/25.
 */

public class FileReader {

    public FileReader(Context context){
        mContext = context;
    }
    private static Context mContext;
    private static int mResourceId;

    public ArrayList processFile(int resourceId)
    {
        mResourceId = resourceId;
        ArrayList contentList = new ArrayList();

        String jsonStr = this.readRawTextFile();
        try {
            contentList = this.parseJsonFromString(jsonStr);
        } catch(Exception e){
            e.printStackTrace();
        }

        return contentList;
    }

    private static String readRawTextFile()
    {
        InputStream inputStream = mContext.getResources().openRawResource(mResourceId);

        InputStreamReader inputreader = new InputStreamReader(inputStream);
        BufferedReader buffreader = new BufferedReader(inputreader);
        String line;
        StringBuilder text = new StringBuilder();

        try {
            while (( line = buffreader.readLine()) != null) {
                text.append(line);
            }
        } catch (IOException e) {
            return null;
        }

        return text.toString();
    }



    private ArrayList parseJsonFromString(String jsonString)
        throws JSONException {

        ArrayList contentList = new ArrayList();

        try {
            JSONObject contentJson = new JSONObject(jsonString);


            JSONArray fieldArray = contentJson.getJSONArray("fields");

            for(int i = 0; i < fieldArray.length(); i++) {
                String basicField="", additionalField="";

                JSONObject fieldDetails = fieldArray.getJSONObject(i);

                if (!fieldDetails.isNull("additional")) { additionalField = fieldDetails.getString("additional"); }
                if (!fieldDetails.isNull("basic")) { basicField = fieldDetails.getString("basic"); }


                FieldMapping newContent = new FieldMapping( basicField, additionalField);

                contentList.add(newContent);
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }

        return contentList;
    }
}